import os
import json

import requests
import MySQLdb

# import aliyunProvince
import pdb
import random
import time
def update_geeks(cursor, js, id):
    try:
        locationId = js['data']['data']['account']['locationId']
        email = js['data']['data']['account']['email']
        career = js['data']['data']['geek'].get('career','')
        careerLevel = js['data']['data']['geek'].get('careerLevel','')
    except Exception as e:
        print(e)
        pdb.set_trace()
    sql_statement = 'update geek set locationId = \'{0}\', email = \'{1}\', career = \'{2}\', careerLevel = \'{3}\' where id = \'{4}\''.format(
        locationId, email, career, careerLevel, id
        )
    try:
        cursor.execute(sql_statement)
    except Exception as e:
        print(e)
        pdb.set_trace()
           
if __name__ == '__main__':
    db = MySQLdb.connect(host="localhost", user="volunteer_geek", passwd="volunteer_geek", port=3306, db='volunteer_geek', charset='utf8mb4')
    cursor = db.cursor()
    BASE_URL = 'https://greencode.aliyun.com/ajax/geekAjax/geekDetail.json'
    payload = {'geekId':0}
    sql_select_statement = 'select id from geek where locationId is null'
    cursor.execute(sql_select_statement)
    for i in cursor.fetchall():
        payload['geekId'] = int(i[0])
        r = requests.get(BASE_URL, params=payload)
        js = json.loads(r.text)
        if(js['code']!='0'):
            pdb.set_trace()
        # save the result to local database        
        update_geeks(cursor, js, i[0])
        db.commit()
        print('finish %s' % i)
        # sleep for random time
        time.sleep(random.random())